import {
  userLoginApi,
  getUserInfoApi,
  getUserRoutesApi,
  userLogoutApi,
  getUserBtnsApi
} from '@/api'
import { getToken, setToken, removeToken, getBtnCodes, setBtnCodes, removeBtnCodes } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menus: '', // 新增
    btnCodes: getBtnCodes() || []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 新增
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_BTNOBJS: (state, objs) => {
    state.btnCodes = objs
  }
}

const actions = {
  // user login
  loginAction({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      userLoginApi({ username: username.trim(), password: password })
        .then(response => {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          console.log(error)
          reject(error)
        })
    })
  },

  // get user info
  getUserInfoAction({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfoApi(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            return reject('Verification failed, please Login again.')
          }

          const { name, avatar } = data

          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取动态路由
  getUserRoutesAction({ commit }) {
    return new Promise((resolve, reject) => {
      getUserRoutesApi().then(response => {
        const { items } = response.data
        if (!items) {
          reject('验证失败,请重新登录')
        }
        // 将后台传过来的list转成路由格式
        // const menus = changeListToMenu(items)
        const menus = items
        // 如果需要404.请在此处添加
        menus.push(
          {
            path: '/404',
            component: '/404',
            hidden: true
          },
          {
            path: '*',
            redirect: '/404',
            hidden: true
          }
        )
        commit('SET_MENUS', menus) // 触发vuex SET_MENUS 将 路由表保存到vuex中
        resolve()
      })
    })
  },
  // 获取动态按钮权限码
  getUserBtnsAction({ commit }) {
    return new Promise((resolve, reject) => {
      getUserBtnsApi().then(response => {
        const { items } = response.data
        if (!items) {
          reject('验证失败,请重新登录')
        }

        const btns = []
        items.forEach(item => {
          btns.push(item.code)
        })
        commit('SET_BTNOBJS', btns) // 触发vuex SET_MENUS 将 路由表保存到vuex中
        setBtnCodes(btns)
        resolve()
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      userLogoutApi(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          removeBtnCodes()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
